//
//  PlayMusicViewController.swift
//  Ios项目forQQ音乐
//
//  Created by Ann on 2017/9/20.
//  Copyright © 2017年 Ann. All rights reserved.
//

import UIKit
import SnapKit
import AVFoundation

class PlayMusicViewController: UIViewController {

     
    var musicListModel = MusicListViewModel()
    
    var timerForProgress :Timer?
    
    var lrcTimer : CADisplayLink?
    
    var rotationAnim:CABasicAnimation?
    
    //4.需要准备默认播放曲目属性
    var currentMusic:MusicViewModel?{
        //MARK:Step 4.歌曲界面信息完善
        didSet{
            songTitle.text = currentMusic?.musicModel.name
            songSingle.text = currentMusic?.musicModel.singer
            trueImageView.image = UIImage(named: currentMusic?.musicModel.icon ?? "")
            
         
            
            //6.10  歌词名字赋值给tableView
            lrcScrollView.lrcname =  currentMusic?.musicModel.lrcname
         
            
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        musicPlayOrPause()
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        setupUI()
        lodingMusicList()
        //4.4 默认曲目初始化
        currentMusic = musicListModel.musicList[6]
        
        
    }
    //MARK:Step 0 .准备工作
    //0.1 创建相关文件目录
    //0.2 使用cocoapods安装‘SnapKit’自动布局框架
    //0.3 将需要素材倒入项目
    
    //MARK:Step 1 .搭建界面
    
    //1 懒加载界面需要的控件属性

    
    //1.1 左上关闭按钮
    lazy var closeButton:UIButton = {
        
        let b = UIButton()
        b.setImage(UIImage.init(named: "miniplayer_btn_playlist_close"), for: UIControlState.normal)
        return b
        
    }()
    
    //1.2 右上曲目细节按钮
    lazy var detailButton:UIButton = {
        
        let b = UIButton()
        b.setImage(UIImage.init(named: "main_tab_more_h"), for: UIControlState.normal)
        b.tintColor = UIColor.darkGray
        b.sizeToFit()
        return b
    }()
    
    //1.3顶部歌名文本
    lazy var songTitle:UILabel = {
        
        let lab = UILabel()
        lab.textColor = UIColor.white
        lab.text = "歌曲名称"
        lab.sizeToFit()
        return lab
    }()
    
    //1.4歌手名文本
    lazy var songSingle:UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.lightGray
        lab.text = "歌手"
        lab.sizeToFit()
        return lab
    }()
    
    //1.5 CD圆盘边框图层
    lazy var bgImageView:UIImageView = {
        let bgV = UIImageView()
        bgV.backgroundColor = UIColor.darkGray
        return bgV
    }()
    
    //1.5.1 专辑图片
    lazy var trueImageView:UIImageView = {
        let imgV = UIImageView()
        imgV.backgroundColor = UIColor.red
        imgV.image = UIImage.init(named: "ddd")
        
        return imgV
    }()
    
    //1.6 歌词文本
    lazy var lrcLabel:UILabel = {
        let lb = UILabel()
        lb.textColor = UIColor.lightGray
        lb.text = ""
        return lb
    }()
    
    //1.6.1 歌词文本
    lazy var lrcLabelTwo:UILabel = {
        let lb = UILabel()
        lb.textColor = UIColor.lightGray
        lb.text = ""
        return lb
    }()
    //1.7 曲目进度条
    lazy var progressSlider:UISlider = {
        let sv = UISlider()
        sv.minimumTrackTintColor = UIColor.init(red: 51/255, green: 194/255, blue: 124/255, alpha: 1)
        sv.thumbTintColor =  UIColor.init(red: 51/255, green: 194/255, blue: 124/255, alpha: 1)
        return sv
    }()
    
    //1.8 曲目进度时间
    lazy var currentPlayLabel:UILabel = {
        
        let lb = UILabel()
        lb.text = "00:00"
        lb.textColor = UIColor.white
        lb.font = UIFont.systemFont(ofSize: 10)
        lb.sizeToFit()
        return lb
    }()
    
    //1.9 曲目时长
    lazy var totalPlayLabel:UILabel = {
        
        let lb = UILabel()
        lb.text = "00:00"
        lb.textColor = UIColor.white
        lb.font = UIFont.systemFont(ofSize: 10)
        lb.sizeToFit()
        return lb
    }()
    
    //1.10 上一首按钮
    lazy var previousSong:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage.init(named: "player_btn_pre_normal"), for: .normal)
        
        return btn
        
    }()
    
    //1.11 下一首按钮
    lazy var nextSong:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage.init(named: "player_btn_next_normal"), for: .normal)
        
        return btn
        
    }()
    
    //1.12 播放/暂停 按钮
    lazy var playOrpauseButton:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage.init(named: "player_btn_play_normal"), for: .normal)
        
        btn.sizeToFit()
        return btn
        
    }()
    
    //1.13 蒙版背景/毛玻璃背景
    lazy var bgView:UIImageView = {
        let v = UIImageView()
        v.image = UIImage.init(named: "ddd")
        
        return v
    }()
    //MARK:Step 6.添加一个scrollView,显示歌词
    //6.1 懒加载控件
    //6.4 自定义LrcScrollView
    lazy var lrcScrollView :LrcScrollView = {
        
        let sv = LrcScrollView()
        return sv
    }()
    
    

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

 


}
//MARK:Step 2.加载音乐数据(加载plist文件)



extension PlayMusicViewController{
 
    //2.1 加载列表数据
    func lodingMusicList(){
            musicListModel.loadMusicList { (isSuccessed) in
                guard isSuccessed else{
                    print("数据加载出错")
                return
                }
          
                
        }
    }
    
}
extension PlayMusicViewController{
   
    func addRotationAnim() {
       //3.7.1 创建动画(CABasic/KeyFrame)
        rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
        
        //3.7.2 设置动画的属性
        rotationAnim?.fromValue = 0
        rotationAnim?.toValue = M_PI * 2
        rotationAnim?.repeatCount = MAXFLOAT
        rotationAnim?.duration = 30
        
        rotationAnim?.isRemovedOnCompletion = false
       
        
        guard let animCA = rotationAnim else {
            return
        }
        //3.7.3 将动画添加到layer中
        trueImageView.layer.add(animCA, forKey: nil)
    }
    
    func setupUI(){
    
        //1.14 控件添加到view
        view.addSubview(bgView)
        view.addSubview(songSingle)
        view.addSubview(songTitle)
        view.addSubview(closeButton)
        view.addSubview(detailButton)
        view.addSubview(bgImageView)
        view.addSubview(trueImageView)
        view.addSubview(lrcLabel)
        view.addSubview(lrcLabelTwo)
        view.addSubview(currentPlayLabel)
        view.addSubview(totalPlayLabel)
        view.addSubview(previousSong)
        view.addSubview(nextSong)
        view.addSubview(playOrpauseButton)
        //LrcScrollView添加
        setupLrcScrollView()
        view.addSubview(progressSlider)
        
       
        
        
        //1.15 设置自动布局
        layoutIconWithSnapKit()
        
        //1.16 对专辑视图圆角化
        view.layoutIfNeeded()
        setupIconViewCorner()
        
        //1.17 对歌手背景视图的毛玻璃化处理//找张图片顶替看预设效果
        setupBlurView()
        
     
        
        //MARK:Step 3.对按钮的处理，添加相应监听事件,能播放音乐
        addTargetToIcon()
        
        //MARK:Step 5.歌曲进度条的完善
        addTargetToSlider()
        
    }
    
    //6.3 完善lrcScrollView
    func setupLrcScrollView(){
        view.addSubview(lrcScrollView)
        //lrcScrollView.backgroundColor = UIColor.yellow
        lrcScrollView.contentSize = CGSize(width: CGFloat( UIScreen.main.bounds.width * 2 ), height: 0)
        lrcScrollView.isPagingEnabled = true
        lrcScrollView.showsHorizontalScrollIndicator = false
        lrcScrollView.lrcDelegate = self
        lrcScrollView.delegate = self
    }
    

    
        //毛玻璃
      func setupBlurView() {
        let blurEffect = UIBlurEffect(style: .dark)
        let blurView = UIVisualEffectView(effect: blurEffect)
        blurView.frame = CGRect(x: 0, y: 0, width: 414, height: 667)
        blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        bgView.addSubview(blurView)
    }
    
    //圆角
    private func setupIconViewCorner() {
        
        bgImageView.layer.cornerRadius = CGFloat(bgImageView.frame.width/2)
        bgImageView.layer.masksToBounds = true
        
        trueImageView.layer.cornerRadius = CGFloat(trueImageView.frame.width/2)
        trueImageView.layer.masksToBounds = true
        
    }
    
    func layoutIconWithSnapKit(){
        
       //蒙版背景
        bgView.frame = view.bounds
  
        //使用前记得import 头文件
     
        
        //歌名
        songTitle.snp.makeConstraints { (make) in
            make.top.equalTo(topLayoutGuide.snp.bottom)
            make.centerX.equalTo(view.snp.centerX)
            
        }
        //歌手名称
        songSingle.snp.makeConstraints { (make) in
            make.top.equalTo(songTitle.snp.bottom).offset(10)
            
            make.centerX.equalTo(songTitle.snp.centerX)
        }
        //关闭按钮
        closeButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(songTitle.snp.centerY)
            make.left.equalTo(view.snp.left).offset(5)
            make.height.width.equalTo(detailButton.snp.height)
        }
        //歌曲详情
        detailButton.snp.makeConstraints { (m) in
            m.centerY.equalTo(songTitle.snp.centerY)
            m.right.equalTo(view.snp.right).offset(-5)
        }
        
        //专辑图片
        bgImageView.snp.makeConstraints { (m) in
            m.width.height.equalTo(250)
            m.top.equalTo(songTitle.snp.bottom).offset(45)
            m.centerX.equalTo(view.snp.centerX)
        }
        
        trueImageView.snp.makeConstraints { (m) in
            m.width.height.equalTo(240)
            m.center.equalTo(bgImageView)
        }
        
        
        //歌词
        lrcLabel.snp.makeConstraints { (make) in
            make.top.equalTo(bgImageView.snp.bottom).offset(5)
            make.centerX.equalTo(bgImageView.snp.centerX)
            
        }
        lrcLabelTwo.snp.makeConstraints { (make) in
            make.top.equalTo(lrcLabel.snp.bottom).offset(5)
            make.centerX.equalTo(lrcLabel.snp.centerX)
            
        }

        
        //make break from last
        //暂停or开始
        playOrpauseButton.snp.makeConstraints { (make) in
            make.bottom.equalTo(view.snp.bottom).offset(-20)
            make.centerX.equalTo(view.snp.centerX)
        }
        //上一首
        previousSong.snp.makeConstraints { (make) in
            make.right.equalTo(playOrpauseButton.snp.left).offset(-20)
            make.centerY.equalTo(playOrpauseButton.snp.centerY)
            
        }
        //下一首
        nextSong.snp.makeConstraints { (make) in
            make.left.equalTo(playOrpauseButton.snp.right).offset(20)
            make.centerY.equalTo(playOrpauseButton.snp.centerY)
        }
        //进度条
        progressSlider.snp.makeConstraints { (make) in
            make.top.equalTo(playOrpauseButton.snp.top).offset(-40)
            make.centerX.equalTo(playOrpauseButton.snp.centerX)
            make.width.equalTo(view.bounds.width - currentPlayLabel.bounds.width - totalPlayLabel.bounds.width-5)
            make.height.equalTo(4)
            
            
        }
        //播放进度文本
        currentPlayLabel.snp.makeConstraints { (make) in
            make.left.equalTo(view.snp.left)
            
            make.centerY.equalTo(progressSlider.snp.centerY)
            
        }
        
        //歌曲时长
        
        totalPlayLabel.snp.makeConstraints { (make) in
            
            make.right.equalTo(view.snp.right)
            make.centerY.equalTo(progressSlider.snp.centerY)
            
        }
        //6.2 布局lrcScrollView
        lrcScrollView.snp.makeConstraints { (make) in
            make.top.equalTo(songSingle.snp.bottom).offset(10)
            make.left.equalTo(view.snp.left)
            make.right.equalTo(view.snp.right)
            make.bottom.equalTo(progressSlider.snp.top).offset(-10)
        }
    
    
    }
    
}

//
extension PlayMusicViewController{

    
    
     //MARK:Step 7.显示歌词的处理
    
   //7.1 添加歌词计时器
    func addLrcTimer() {
        lrcTimer = CADisplayLink(target: self, selector: #selector(updateLrc))
        lrcTimer?.add(to: RunLoop.main, forMode: .commonModes)
    }
   
    func updateLrc(){
        //获取实时歌曲播放进度时间
        lrcScrollView.currentTime = MusicTools.sharePlayer.getCurrentTime()
    }
   //移除
    func removeLrcTimer (){
        lrcTimer?.invalidate()
        lrcTimer = nil
    }
    
    
    
    
    
    func addTargetToIcon(){
        //3.1监听播放&暂停按钮
        playOrpauseButton.addTarget(self, action: Selector("musicPlayOrPause"), for: .touchUpInside)
        
        nextSong.addTarget(self, action: Selector("nextOne"), for:.touchUpInside)
        
        previousSong.addTarget(self, action: Selector("previousOne"), for: .touchUpInside)
        
       
        
        
        
        
    }
    
    //3.1.1播放&暂停按钮实现方法
    
    func musicPlayOrPause (){
       
        guard let name = currentMusic?.musicModel.filename else {
            
            return
        }
         //3.1.2需要准备 解析曲目的工具类MusicTools
        
        //3.3 音频是否在播放，为真则
        if  MusicTools.sharePlayer.player?.isPlaying == true {
            //暂停
            //3.8 暂停动画旋转
            trueImageView.layer.pauseAnim()
           
            MusicTools.sharePlayer.pausePlayer()
            
            playOrpauseButton.setImage(UIImage.init(named: "player_btn_play_normal"), for: .normal)
            
          //7.5 关闭歌词计时器
            removeLrcTimer()
            
            
        }else{
            
            //播放音乐
            //3.9 继续动画旋转
             trueImageView.layer.resumeAnim()
            
            playMusic()
            
            playOrpauseButton.setImage(UIImage.init(named: "player_btn_pause_normal"), for: .normal)
          
            
            
        }
        
        
    }
    //播放音乐都进过这里
    func playMusic(){
         //3.7 添加旋转动画
        if rotationAnim == nil {
            addRotationAnim()
        }
       
        MusicTools.sharePlayer.playMusic(musicName: currentMusic?.musicModel.filename ?? "")
        
        //5.1将时间格式化再赋值
        totalPlayLabel.text = MusicTools.sharePlayer.getDuration().stringByTime()
        
        addTimer()
        //7.4 启动计时器
        addLrcTimer()
       
        
       MusicTools.sharePlayer.delegateOfAVAudioPlayerDelegate(delegate: self as! AVAudioPlayerDelegate)
        
        
    }
    
    
    
    
    //3.5 下一首歌按钮方法实现
    func nextOne(){
        
       whichLastOrNext(isNext: true)
        
    }
    
    //3.6 下一首歌按钮方法实现
    func previousOne(){
        
      whichLastOrNext(isNext: false)
        
        
        
    }
    //上下曲目选择抽取
    func whichLastOrNext(isNext:Bool){
        
        guard currentMusic != nil else {
            print("currentMusic==nil !!")
            return
        }
        
        let currentIndex = musicListModel.musicList.index(of: currentMusic!)
        
        var nextIndex = 0
        
        if isNext {
            
            nextIndex = currentIndex! + 1
            
            if nextIndex > musicListModel.musicList.count - 1  {
                
                nextIndex = 0
                
            }
            
            currentMusic = musicListModel.musicList[nextIndex]
            
            //播放下一首
            MusicTools.sharePlayer.pausePlayer()
            playMusic()
            playOrpauseButton.setImage(UIImage.init(named: "player_btn_pause_normal"), for: .normal)
            
        }else{
           nextIndex = currentIndex! - 1
            
            if nextIndex < 0  {
                
                nextIndex = musicListModel.musicList.count - 1
            }
            currentMusic = musicListModel.musicList[nextIndex]
            
            //播放上一首
            MusicTools.sharePlayer.pausePlayer()
            playMusic()
            playOrpauseButton.setImage(UIImage.init(named: "player_btn_pause_normal"), for: .normal)
            
            
        }
        }
    
    func addTargetToSlider(){
        
        //5.1 监听进度条各个事件
        progressSlider.addTarget(self, action: Selector("sliderTouchUpInside"), for: UIControlEvents.touchUpInside)
        
        progressSlider.addTarget(self, action: Selector("sliderTouchUpOutside"), for: UIControlEvents.touchUpOutside)
        
        progressSlider.addTarget(self, action: Selector("slidertouchDown"), for: UIControlEvents.touchDown)
        
    }
    
    func sliderTouchUpOutside(){
        
        setCTime()
    }
    func sliderTouchUpInside(){
        setCTime()
        
    }
    //5.1.1 重置播放位置
    func setCTime(){
        
        let time = Double(progressSlider.value) * MusicTools.sharePlayer.getDuration()
        //从当前百分比播放
        MusicTools.sharePlayer.setPlayCurrentTime(ct: time)
        //5.1.2 给进度条添加记时器
     //   addTimer()
    }
    
    func slidertouchDown(){
        
        //5.1.2移除计时器
        removeProgressTimer()
        
    }
    
    //添加计时器
    func addTimer(){
        //5.1.3 全局变量 Timer
        timerForProgress = Timer(timeInterval: 1.0, target: self, selector: Selector("updateProgress"), userInfo: nil, repeats: true)
        
        RunLoop.main.add(timerForProgress!, forMode: RunLoopMode.commonModes)
        
        
    }
    func updateProgress(){
        
        currentPlayLabel.text = MusicTools.sharePlayer.getCurrentTime().stringByTime()
        progressSlider.value = Float(MusicTools.sharePlayer.getCurrentTime() / MusicTools.sharePlayer.getDuration())
        
    }
    func removeProgressTimer (){
        timerForProgress?.invalidate()
        timerForProgress = nil
    }

    
    
    
    
    
    
    

}
extension PlayMusicViewController: AVAudioPlayerDelegate{

    
    
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
          if flag{
            nextOne()
            
        }
    }
}
//UIScrollView 代理
extension PlayMusicViewController:LrcScrollViewDelegate,UIScrollViewDelegate{
    //7.6 滚动scrollView背景透明效果
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let ratio = scrollView.contentOffset.x / scrollView.bounds.width
        
        lrcLabel.alpha = 1 - ratio
        trueImageView.alpha = 1 - ratio
        bgImageView.alpha = 1 - ratio
        lrcLabelTwo.alpha = 1 - ratio
    }
    //7.9 代理实现
    func lrcScrollView(lrcScrollView: LrcScrollView, nextLrcText: String, currentLrcText: String, preLrcText: String) {
        lrcLabel.text = currentLrcText
        lrcLabelTwo.text = nextLrcText
    }
}

 
